package com.example.jimuyutabletcontrol.activity;

import android.animation.AnimatorSet;
import android.animation.ValueAnimator;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.graphics.Point;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.Overlay;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.utils.CoordinateConverter;
import com.example.jimuyutabletcontrol.R;
import com.example.jimuyutabletcontrol.database.DBHelperSend;
import com.example.jimuyutabletcontrol.database.TaskContainer;
import com.example.jimuyutabletcontrol.network.udp.UdpSocket;
import com.example.jimuyutabletcontrol.utils.Constants;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.marcoscg.headerdialog.HeaderDialog;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.appcompat.app.AppCompatActivity;

public class FixTaskMapActivity extends AppCompatActivity implements View.OnClickListener {
    private String auvcode;
    private Button loadTaskbyDatabase;
    private Button addLocationPointFixMap;
    private Button canclePointFixMap;
    private Button saveDataFixMap;
    private Button loadTaskbyFile;
    private Button checkData;

    public TaskContainer taskContainer;

    private MapView mapView;
    public BaiduMap baiduMap;
    private HeaderDialog headerMarkerDialog;
    private HeaderDialog headerAddGPSDialog;

    private int ID;
    private List<Overlay> mMarkerListOverlayMission;
    private List<LatLng> mLatLngListMission;
    private List<Overlay> mPolylineListOverlayMission;
    private int checkpolymission;

    private Boolean keep;//需要先加载数据，才能操作其他

    private Map<Integer, String> mapIntToString;

    private int[] marker = {
            R.drawable.taskmap_icon_marka, R.drawable.taskmap_icon_markb,
            R.drawable.taskmap_icon_markc, R.drawable.taskmap_icon_markd,
            R.drawable.taskmap_icon_marke, R.drawable.taskmap_icon_markf,
            R.drawable.taskmap_icon_markg, R.drawable.taskmap_icon_markh,
            R.drawable.taskmap_icon_marki, R.drawable.taskmap_icon_markj
    };

    private Point[] pentagonVertices;
    private FloatingActionButton fabTools;
    private FloatingActionButton fabSend;
    private Button[] buttonsTools;
    private Button[] buttonsSend;
    private int startPositionX;
    private int startPositionY;
    private int toolsWhichAnimation;
    private int sendWhichAnimation;
    private int[] enterDelay = {0, 40, 80, 120, 160, 200, 240};
    private int[] exitDelay = {0, 40, 80, 120, 160, 200, 240};
    private Boolean isFabToolsClicked = false;
    private Boolean isFabSendClicked = false;

    private static FixTaskMapActivity self;

    public static FixTaskMapActivity getInstance() {
        return self;
    }

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fixtaskmapinterface_activity);
        this.self = this;
        mapView = findViewById(R.id.bmapViewfixtaskmap);
        baiduMap = mapView.getMap();
        MapStatus.Builder builder = new MapStatus.Builder();
        builder.zoom(4.0f);
        baiduMap.setMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
        auvcode = getIntent().getStringExtra("IMEI");
        initResource();
        setClickListener();
        prepareFloatButton();
    }

    private void initResource() {
        mapIntToString = new HashMap<>(10);
        mapIntToString.put(0, "A");
        mapIntToString.put(1, "B");
        mapIntToString.put(2, "C");
        mapIntToString.put(3, "D");
        mapIntToString.put(4, "E");
        mapIntToString.put(5, "F");
        mapIntToString.put(6, "G");
        mapIntToString.put(7, "H");
        mapIntToString.put(8, "I");
        mapIntToString.put(9, "J");
        refreshData();
        keep = false;
    }

    private void refreshData() {
        if (mMarkerListOverlayMission != null) {
            mMarkerListOverlayMission.clear();
        }
        mMarkerListOverlayMission = new ArrayList<>();
        if (mLatLngListMission != null) {
            mLatLngListMission.clear();
        }
        mLatLngListMission = new ArrayList<>();
        if (mPolylineListOverlayMission != null) {
            mPolylineListOverlayMission.clear();
        }
        mPolylineListOverlayMission = new ArrayList<>();
        checkpolymission = 0;
        if (taskContainer != null) {
            taskContainer.clear();
        }
        taskContainer = new TaskContainer();
        String GPSINFO = DBHelperSend.getInstance().getGpsInfo(auvcode);
        System.out.println("GPSINFO: " + GPSINFO);
        if (GPSINFO != null) {
            taskContainer.loadData(GPSINFO);
        }
    }

    public void refreshDataWithoutLoad() {
        if (mMarkerListOverlayMission != null) {
            mMarkerListOverlayMission.clear();
        }
        mMarkerListOverlayMission = new ArrayList<>();
        if (mLatLngListMission != null) {
            mLatLngListMission.clear();
        }
        mLatLngListMission = new ArrayList<>();
        if (mPolylineListOverlayMission != null) {
            mPolylineListOverlayMission.clear();
        }
        mPolylineListOverlayMission = new ArrayList<>();
        checkpolymission = 0;
    }

    private void setClickListener() {
        baiduMap.setOnMapLongClickListener(listener);
        baiduMap.setOnMarkerClickListener(listener1);
    }

    public void addMissionPointToMapWithoutLoad(LatLng btlatLng, LatLng rlatLng) {
        if (checkpolymission <= 9) {
            BitmapDescriptor bitmap = BitmapDescriptorFactory
                    .fromResource(marker[checkpolymission]);
            Bundle bundle = new Bundle();
            bundle.putInt("ID", checkpolymission);
            OverlayOptions option = new MarkerOptions()
                    .position(btlatLng)
                    .icon(bitmap)
                    .extraInfo(bundle);
            checkpolymission++;
            Overlay overlay = baiduMap.addOverlay(option);
            mMarkerListOverlayMission.add(overlay);
            mLatLngListMission.add(btlatLng);
        } else {
            toastMsg("标点超过限制数10个");
        }
    }

    private void addMissionPointToMap(LatLng btlatLng, LatLng rlatLng) {
        if (checkpolymission <= 9) {
            if (checkpolymission + 1 > taskContainer.getTaskSize()) {
                taskContainer.addPoint(rlatLng);
            }
            BitmapDescriptor bitmap = BitmapDescriptorFactory
                    .fromResource(marker[checkpolymission]);
            Bundle bundle = new Bundle();
            bundle.putInt("ID", checkpolymission);
            OverlayOptions option = new MarkerOptions()
                    .position(btlatLng)
                    .icon(bitmap)
                    .extraInfo(bundle);

            checkpolymission++;

            /*
            if (checkpolymission > 1) {
                LatLng point1 = mLatLngListMission.get(checkpolymission - 2);
                LatLng point2 = btlatLng;
                List<LatLng> points = new ArrayList<>();
                points.add(point1);
                points.add(point2);
                OverlayOptions mOverlayOptions = new PolylineOptions()
                        .width(10)
                        .color(Color.MAGENTA)
                        .points(points);
                Overlay mPolyline = baiduMap.addOverlay(mOverlayOptions);
                mPolylineListOverlayMission.add(mPolyline);
            }
            */

            Overlay overlay = baiduMap.addOverlay(option);
            mMarkerListOverlayMission.add(overlay);
            mLatLngListMission.add(btlatLng);
        } else {
            toastMsg("标点超过限制数10个");
        }
    }

    private LatLng gpsToBaidu(LatLng point) {
        CoordinateConverter converter = new CoordinateConverter();
        converter.from(CoordinateConverter.CoordType.GPS);
        converter.coord(point);
        LatLng changePoint = converter.convert();

        return changePoint;
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    };

    private void toastMsg(final String msg) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
            }
        });
    }

    BaiduMap.OnMapLongClickListener listener = new BaiduMap.OnMapLongClickListener() {
        @Override
        public void onMapLongClick(LatLng latLng) {
            Log.e("OnMapLongClickListener", "" + keep);
            if (keep) {
                addMissionPointToMap(latLng, baiduToGps(latLng));
            } else {
                toastMsg("请先加载任务");
            }
        }
    };

    BaiduMap.OnMarkerClickListener listener1 = new BaiduMap.OnMarkerClickListener() {
        @Override
        public boolean onMarkerClick(Marker marker) {
            System.out.println("I am in on Marker FixTaskMap");
            ID = marker.getExtraInfo().getInt("ID");
            headerMarkerDialog = null;
            createHeaderMarkerDialog();
            EditText fixMapEditSpeed = headerMarkerDialog.getInflatedView().findViewById(R.id.fixmapeditspeed);
            EditText fixMapEditDepth = headerMarkerDialog.getInflatedView().findViewById(R.id.fixmapeditdepth);
            EditText fixMapEditLatitude = headerMarkerDialog.getInflatedView().findViewById(R.id.fixmapeditlatitude);
            EditText fixMapEditLongtitude = headerMarkerDialog.getInflatedView().findViewById(R.id.fixmapeditlongtitude);
            fixMapEditSpeed.setText("0");
            fixMapEditDepth.setText("0");
            fixMapEditLatitude.setText("0");
            fixMapEditLongtitude.setText("0");
            if (taskContainer.getDepths().size() > ID) {
                fixMapEditSpeed.setText(taskContainer.getRotates().get(ID));
                fixMapEditDepth.setText(taskContainer.getDepths().get(ID));
            }
            System.out.println("ID: " + ID);
            System.out.println("taskContainer Size: " + taskContainer.getTaskSize());
            LatLng point = taskContainer.getPoints().get(ID);//TODO
            fixMapEditLatitude.setText("" + point.latitude);
            fixMapEditLongtitude.setText("" + point.longitude);

            //alertMarkerDialog.setTitle(mapIntToString.get(ID) + "点处航行参数");
            headerMarkerDialog.show();
            return true;
        }
    };

    private void createHeaderMarkerDialog() {
        headerMarkerDialog = new HeaderDialog(this);
        headerMarkerDialog.setColor(getResources().getColor(R.color.Control3)) // Sets the header background color
                .setElevation(false) // Sets the header elevation, true by default
                .setIcon(getResources().getDrawable(R.drawable.ic_content_paste_black_24dp)) // Sets the dialog icon image
                .setTitle(getResources().getString(R.string.addparameter)) // Sets the dialog title
                .setMessage("请在下面修改任务" + mapIntToString.get(ID) + "点的数据") // Sets the dialog message
                .justifyContent(true) // Justifies the message text, false by default
                .setTitleColor(Color.parseColor("#212121")) // Sets the header title text color
                .setIconColor(Color.parseColor("#212121")) // Sets the header icon color
                .setTitleGravity(Gravity.CENTER_HORIZONTAL) // Sets the header title text gravity
                .setMessageGravity(Gravity.CENTER_HORIZONTAL) // Sets the message text gravity
                .setTitleMultiline(false) // Multiline header title text option, true by default
                .setView(R.layout.fixtaskmap_dialog) // Set custom view to the dialog (only possible via layout resource)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        EditText fixMapEditSpeed = headerMarkerDialog.getInflatedView().findViewById(R.id.fixmapeditspeed);
                        EditText fixMapEditDepth = headerMarkerDialog.getInflatedView().findViewById(R.id.fixmapeditdepth);
                        EditText fixMapEditLatitude = headerMarkerDialog.getInflatedView().findViewById(R.id.fixmapeditlatitude);
                        EditText fixMapEditLongtitude = headerMarkerDialog.getInflatedView().findViewById(R.id.fixmapeditlongtitude);
                        String check1 = fixMapEditSpeed.getText().toString();
                        String check2 = fixMapEditDepth.getText().toString();
                        double check3 = Double.valueOf(fixMapEditLatitude.getText().toString());
                        double check4 = Double.valueOf(fixMapEditLongtitude.getText().toString());
                        if (check3 < 90 && check3 > -90 && check4 < 180 && check4 > -180) {
                            if (ID < taskContainer.getDepthsSize()) {
                                taskContainer.updateRotate(check1, ID);
                                taskContainer.updateDepth(check2, ID);
                                taskContainer.updatePoint(new LatLng(check3, check4), ID);
                                baiduMap.clear();
                                refreshDataWithoutLoad();
                                for (int i = 0; i < taskContainer.getTaskSize(); i++) {
                                    LatLng point = taskContainer.getPoints().get(i);
                                    addMissionPointToMapWithoutLoad(gpsToBaidu(point), point);
                                }
                            } else if (((int) Double.parseDouble(check1) != 0 && (int) Double.parseDouble(check2) != 0)
                                    || !check1.contentEquals("") || !check2.contentEquals("")) {
                                taskContainer.addRotate(check1);
                                taskContainer.addDepth(check2);
                            }
                        }
                        toastMsg("已记录" + mapIntToString.get(ID) + "点处航行参数");
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                }).create();
    }

    private void createHeaderAddGPSDialog() {
        headerAddGPSDialog = new HeaderDialog(this);
        headerAddGPSDialog.setColor(getResources().getColor(R.color.Control3)) // Sets the header background color
                .setElevation(false) // Sets the header elevation, true by default
                .setIcon(getResources().getDrawable(R.drawable.ic_content_paste_black_24dp)) // Sets the dialog icon image
                .setTitle(getResources().getString(R.string.addparameter)) // Sets the dialog title
                .setMessage("请在下面添加任务" + mapIntToString.get(checkpolymission) + "点的GPS数据") // Sets the dialog message
                .justifyContent(true) // Justifies the message text, false by default
                .setTitleColor(Color.parseColor("#212121")) // Sets the header title text color
                .setIconColor(Color.parseColor("#212121")) // Sets the header icon color
                .setTitleGravity(Gravity.CENTER_HORIZONTAL) // Sets the header title text gravity
                .setMessageGravity(Gravity.CENTER_HORIZONTAL) // Sets the message text gravity
                .setTitleMultiline(false) // Multiline header title text option, true by default
                .setView(R.layout.fixtaskmapaddgps_dialog) // Set custom view to the dialog (only possible via layout resource)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        EditText editLatitudeFixMap = headerAddGPSDialog.getInflatedView().findViewById(R.id.fixmapeditlatitude);
                        EditText editLongtitudeFixMap = headerAddGPSDialog.getInflatedView().findViewById(R.id.fixmapeditlongtitude);

                        String value1 = editLatitudeFixMap.getText().toString();
                        String value2 = editLongtitudeFixMap.getText().toString();
                        if (value1.equals("") || value2.equals("")) {
                            toastMsg("请输入经纬度");
                        } else {
                            double latitude = Double.valueOf(value1);
                            double longtitude = Double.valueOf(value2);
                            System.out.println("latitude: " + latitude);
                            System.out.println("longtitude: " + longtitude);
                            if (latitude > 90 || latitude < -90 || longtitude > 180 || longtitude < -180) {
                                toastMsg("请输入正确的经纬度");
                            } else {
                                LatLng point = new LatLng(latitude, longtitude);
                                toastMsg("已记录" + mapIntToString.get(checkpolymission) + "点处航行参数");
                                addMissionPointToMap(gpsToBaidu(point), point);
                            }
                        }
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                }).create();
    }
    /*
    private void createMarkerDialog() {
        alertMarkerDialog = new AlertDialog.Builder(FixTaskMapActivity.this)
                .setView(view)
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        alertMarkerDialog.dismiss();
                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String check1 = fixMapEditSpeed.getText().toString();
                        String check2 = fixMapEditDepth.getText().toString();
                        double check3 = Double.valueOf(fixMapEditLatitude.getText().toString());
                        double check4 = Double.valueOf(fixMapEditLongtitude.getText().toString());
                        if ( check3 < 90 && check3 > -90 && check4 < 180 && check4 > -180) {
                            if (ID < taskContainer.getDepthsSize()) {
                                taskContainer.updateRotate(check1, ID);
                                taskContainer.updateDepth(check2, ID);
                                taskContainer.updatePoint(new LatLng(check3, check4), ID);
                                baiduMap.clear();
                                refreshDataWithoutLoad();
                                for(int i = 0; i < taskContainer.getTaskSize(); i ++) {
                                    LatLng point = taskContainer.getPoints().get(i);
                                    addMissionPointToMapWithoutLoad(gpsToBaidu(point), point);
                                }
                            } else if (((int)Double.parseDouble(check1) != 0 && (int)Double.parseDouble(check2) != 0)
                                    || !check1.contentEquals("") || !check2.contentEquals("")){
                                taskContainer.addRotate(check1);
                                taskContainer.addDepth(check2);
                            }
                        }
                        toastMsg("已记录" + mapIntToString.get(ID) + "点处航行参数");
                        alertMarkerDialog.dismiss();
                    }
                }).create();
    }

    private void createAddGPSDialog() {
        alertAddGPSDialog = new AlertDialog.Builder(FixTaskMapActivity.this)
                .setTitle("请输入需要添加的GPS数据")
                .setView(addGPSView)
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        alertAddGPSDialog.dismiss();
                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String value1 = editLatitudeFixMap.getText().toString();
                        String value2 = editLongtitudeFixMap.getText().toString();
                        if (value1.equals("") || value2.equals("")) {
                            toastMsg("请输入经纬度");
                        } else {
                            double latitude = Double.valueOf(value1);
                            double longtitude = Double.valueOf(value2);
                            System.out.println("latitude: " + latitude);
                            System.out.println("longtitude: " + longtitude);
                            if (latitude > 90 || latitude < -90 || longtitude > 180 || longtitude < -180) {
                                toastMsg("请输入正确的经纬度");
                            } else {
                                LatLng point = new LatLng(latitude, longtitude);
                                toastMsg("已记录" + mapIntToString.get(checkpolymission) + "点处航行参数");
                                addMissionPointToMap(gpsToBaidu(point), point);
                            }
                        }
                        alertAddGPSDialog.dismiss();
                    }
                }).create();
    }
    */

    private LatLng baiduToGps(LatLng point) {
        double[] gps84 = btogps.btogps.ALLATORIxDEMO(point.latitude, point.longitude);
        return new LatLng(gps84[0], gps84[1]);
    }

    @Override
    public void onClick(View view) {
        boolean isToolsSubClicked = false;
        boolean isSendSubClicked = false;

        switch (view.getId()) {
            case R.id.fabfixtasktool:
                isToolsSubClicked = true;
                isSendSubClicked = true;
                if (!isFabSendClicked) {
                    isFabToolsClicked = true;
                    if (toolsWhichAnimation == 0) {
                        /**
                         * Getting the center point of floating action button
                         *  to set start point of buttons
                         */
                        startPositionX = 2600;
                        startPositionY = 0;
                        for (Button button : buttonsTools) {
                            button.setX(startPositionX);
                            button.setY(startPositionY);
                            button.setVisibility(View.VISIBLE);
                        }
                        for (int i = 0; i < buttonsTools.length; i++) {
                            playEnterAnimation(buttonsTools[i], i);
                        }
                        toolsWhichAnimation = 1;
                    } else {
                        for (int i = 0; i < buttonsTools.length; i++) {
                            playExitAnimation(buttonsTools[i], i);
                        }
                        toolsWhichAnimation = 0;
                        isFabToolsClicked = false;
                    }
                }
                break;
            case R.id.fabfixtasksend:
                isSendSubClicked = true;
                isToolsSubClicked = true;
                if (!isFabToolsClicked) {
                    isFabSendClicked = true;
                    if (sendWhichAnimation == 0) {
                        /**
                         * Getting the center point of floating action button
                         *  to set start point of buttons
                         */
                        startPositionX = 2600;
                        startPositionY = 0;
                        for (Button button : buttonsSend) {
                            button.setX(startPositionX);
                            button.setY(startPositionY);
                            button.setVisibility(View.VISIBLE);
                        }
                        for (int i = 0; i < buttonsSend.length; i++) {
                            playEnterAnimation(buttonsSend[i], i);
                        }
                        sendWhichAnimation = 1;
                    } else {
                        for (int i = 0; i < buttonsSend.length; i++) {
                            playExitAnimation(buttonsSend[i], i);
                        }
                        sendWhichAnimation = 0;
                        isFabSendClicked = false;
                    }
                }
                break;
        }

        if (isFabToolsClicked && !isToolsSubClicked) {
            switch ((int) view.getTag()) {
                case 0:
                    baiduMap.clear();
                    refreshData();
                    keep = true;
                    if (taskContainer.getPoints().size() != 0) {
                        MapStatus.Builder builder = new MapStatus.Builder();
                        builder.zoom(19.0f);
                        baiduMap.setMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
                        LatLng ll = gpsToBaidu(new LatLng(taskContainer.getPoints().get(0).latitude,
                                taskContainer.getPoints().get(0).longitude));
                        MapStatusUpdate status = MapStatusUpdateFactory.newLatLng(ll);
                        baiduMap.animateMapStatus(status);//动画的方式到中间
                        baiduMap.setMyLocationEnabled(true);
                        for (int i = 0; i < taskContainer.getTaskSize(); i++) {
                            LatLng point = taskContainer.getPoints().get(i);
                            addMissionPointToMap(gpsToBaidu(point), point);
                        }
                    } else {
                        toastMsg("所选AUV没有任务数据记录!!!");
                    }
                    break;
                case 1:
                    File file = new File(Constants.FILE_PATH + Constants.TASKMAPFOLDER + Constants.TASKFILE);
                    if (file.exists()) {
                        try {
                            StringBuilder stringBuilder = new StringBuilder();
                            BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
                            String line = bufferedReader.readLine();
                            stringBuilder.append(line + "\n");
                            while (line != null) {
                                line = bufferedReader.readLine();
                                Log.e("萨达", line);
                                stringBuilder.append(line + "\n");
                            }
                            int length = stringBuilder.length();
                            stringBuilder.delete(length - 5, length);
                            if (length != 0) {
                                baiduMap.clear();
                                refreshDataWithoutLoad();
                                keep = true;
                                if (taskContainer != null) {
                                    taskContainer.clear();
                                }
                                taskContainer = new TaskContainer();
                                taskContainer.loadData(stringBuilder.toString());
                                if (taskContainer.getPoints().size() != 0) {
                                    MapStatus.Builder builder = new MapStatus.Builder();
                                    builder.zoom(19.0f);
                                    baiduMap.setMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
                                    LatLng ll = gpsToBaidu(new LatLng(taskContainer.getPoints().get(0).latitude,
                                            taskContainer.getPoints().get(0).longitude));
                                    MapStatusUpdate status = MapStatusUpdateFactory.newLatLng(ll);
                                    baiduMap.animateMapStatus(status);//动画的方式到中间
                                    baiduMap.setMyLocationEnabled(true);
                                    for (int i = 0; i < taskContainer.getTaskSize(); i++) {
                                        LatLng point = taskContainer.getPoints().get(i);
                                        addMissionPointToMap(gpsToBaidu(point), point);
                                    }
                                }
                            }
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                    } else {
                        toastMsg("请把符合格式的文件放到指定位置");
                    }
                    break;
                case 2:
                    headerAddGPSDialog = null;
                    createHeaderAddGPSDialog();
                    headerAddGPSDialog.show();
                    break;
                case 3:
                    if (keep) {
                        if (checkpolymission >= 1) {
                            checkpolymission--;
                        }

                        int lengthMarker = mMarkerListOverlayMission.size();
                        if (lengthMarker >= 1) {
                            mMarkerListOverlayMission.get(lengthMarker - 1).remove();
                            mMarkerListOverlayMission.remove(lengthMarker - 1);
                        }

                        int lengthLiner = mPolylineListOverlayMission.size();
                        if (lengthLiner >= 1) {
                            mPolylineListOverlayMission.get(lengthLiner - 1).remove();
                            mPolylineListOverlayMission.remove(lengthLiner - 1);
                        }

                        int lengthPoint = mLatLngListMission.size();
                        if (lengthPoint >= 1) {
                            mLatLngListMission.remove(lengthPoint - 1);
                        }
                        taskContainer.cancleSet();
                    } else {
                        toastMsg("请先加载任务");
                    }
                    break;
                case 4:
                    int length = taskContainer.getTaskSize();
                    if (length > 1 && keep) {
                        StringBuilder sb = new StringBuilder();
                        for (int i = 0; i < length - 1; i++) {
                            LatLng point = taskContainer.getPoints().get(i);
                            String rotate = "0";
                            String depth = "0";
                            if (taskContainer.checkData(i)) {
                                rotate = taskContainer.getRotates().get(i);
                                depth = taskContainer.getDepths().get(i);
                            }
                            String pointID = mapIntToString.get(i);
                            sb.append(pointID + ":" + point.latitude + "," + point.longitude + "," + rotate + "," + depth + "\n");
                        }
                        LatLng point = taskContainer.getPoints().get(length - 1);
                        String rotate = "0";
                        String depth = "0";
                        if (taskContainer.checkData(length - 1)) {
                            rotate = taskContainer.getRotates().get(length - 1);
                            depth = taskContainer.getDepths().get(length - 1);
                        }
                        String pointID = mapIntToString.get(length - 1);
                        sb.append(pointID + ":" + point.latitude + "," + point.longitude + "," + rotate + "," + depth);
                        DBHelperSend.getInstance().addInfoByIMEI(auvcode, sb.toString());
                        toastMsg("数据保存完毕");
                    } else {
                        toastMsg("无数据需要保存");
                    }
                    break;
                case 5:
                    Intent intent = new Intent(FixTaskMapActivity.this, CheckData.class);
                    intent.putExtra("IMEI", auvcode);
                    startActivity(intent);
                    break;
                case 6:
                    String GPSINFO = DBHelperSend.getInstance().getGpsInfo(auvcode);
                    if (GPSINFO == null) {
                        toastMsg("数据库中无该AUV任务数据");
                    } else {
                        String senddata = "TASKINFO:" + auvcode + "-" + GPSINFO;
                        UdpSocket.getInstance().sendMessage(senddata);
                        toastMsg("发送数据：" + senddata + "\n 完毕");
                    }
                    break;
            }
        }

        if (isFabSendClicked && !isSendSubClicked) {
            Intent intent = null;
            switch ((int) view.getTag()) {
                case 0:
                    intent = new Intent(FixTaskMapActivity.this, MakeTaskMapActivity.class);
                    intent.putExtra("IMEI", auvcode);
                    startActivity(intent);
                    finish();
                    break;
                case 1:
                    intent = new Intent(FixTaskMapActivity.this, MappingActivity.class);
                    startActivity(intent);
                    finish();
                    break;
            }
        }
    }

    private void prepareFloatButton() {
        startPositionX = 0;
        startPositionY = 0;
        toolsWhichAnimation = 0;
        sendWhichAnimation = 0;
        fabTools = findViewById(R.id.fabfixtasktool);
        fabSend = findViewById(R.id.fabfixtasksend);

        fabTools.setOnClickListener(this);
        fabSend.setOnClickListener(this);

        pentagonVertices = new Point[10];
        pentagonVertices[0] = new Point(10, 100);
        pentagonVertices[1] = new Point(10, 280);
        pentagonVertices[2] = new Point(10, 460);
        pentagonVertices[3] = new Point(10, 640);
        pentagonVertices[4] = new Point(10, 820);
        pentagonVertices[5] = new Point(10, 1000);
        pentagonVertices[6] = new Point(10, 1180);

        String[] contentTools = {"后台加载", "文件加载", "添加新点", "删掉末点", "保存数据", "查看数据", "发送数据"};
        String[] contentSend = {"制作任务", "实地测绘"};

        buttonsTools = calculatePentagonVertices(7, contentTools);
        buttonsSend = calculatePentagonVertices(2, contentSend);
    }

    private Button[] calculatePentagonVertices(int number, String[] content) {

        Button[] buttons = new Button[number];

        for (int i = 0; i < buttons.length; i++) {
            //Adding button at (0,0) coordinates and setting their visibility to zero
            buttons[i] = new Button(FixTaskMapActivity.this);
            buttons[i].setLayoutParams(new RelativeLayout.LayoutParams(100, 100));
            buttons[i].setX(0);
            buttons[i].setY(0);
            buttons[i].setTag(i);
            buttons[i].setOnClickListener(this);
            buttons[i].setVisibility(View.INVISIBLE);
            buttons[i].setBackgroundResource(R.drawable.circular_background);
            buttons[i].setTextColor(Color.DKGRAY);
            buttons[i].setText(content[i]);
            buttons[i].setTextSize(14);
            /**
             * Adding those buttons in acitvities layout
             */
            ((LinearLayout) findViewById(R.id.fixtaskmap_main)).addView(buttons[i]);
        }

        return buttons;
    }

    private void playEnterAnimation(final Button button, int position) {

        /**
         * Animator that animates buttons x and y position simultaneously with size
         */
        AnimatorSet buttonAnimator = new AnimatorSet();

        /**
         * ValueAnimator to update x position of a button
         */
        ValueAnimator buttonAnimatorX = ValueAnimator.ofFloat(startPositionX,
                pentagonVertices[position].x);
        buttonAnimatorX.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                button.setX((float) animation.getAnimatedValue());
                button.requestLayout();
            }
        });
        buttonAnimatorX.setDuration(300);

        /**
         * ValueAnimator to update y position of a button
         */
        ValueAnimator buttonAnimatorY = ValueAnimator.ofFloat(startPositionY,
                pentagonVertices[position].y);
        buttonAnimatorY.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                button.setY((float) animation.getAnimatedValue());
                button.requestLayout();
            }
        });
        buttonAnimatorY.setDuration(300);

        /**
         * This will increase the size of button
         */
        ValueAnimator buttonSizeAnimator = ValueAnimator.ofInt(6, 170);
        buttonSizeAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                button.getLayoutParams().width = (int) animation.getAnimatedValue();
                button.getLayoutParams().height = (int) animation.getAnimatedValue();
                button.requestLayout();
            }
        });
        buttonSizeAnimator.setDuration(300);

        /**
         * Add both x and y position update animation in
         *  animator set
         */
        buttonAnimator.play(buttonAnimatorX).with(buttonAnimatorY).with(buttonSizeAnimator);
        buttonAnimator.setStartDelay(enterDelay[position]);
        buttonAnimator.start();
    }

    private void playExitAnimation(final Button button, int position) {

        /**
         * Animator that animates buttons x and y position simultaneously with size
         */
        AnimatorSet buttonAnimator = new AnimatorSet();

        /**
         * ValueAnimator to update x position of a button
         */
        ValueAnimator buttonAnimatorX = ValueAnimator.ofFloat(pentagonVertices[position].x,
                startPositionX);
        buttonAnimatorX.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                button.setX((float) animation.getAnimatedValue());
                button.requestLayout();
            }
        });
        buttonAnimatorX.setDuration(300);

        /**
         * ValueAnimator to update y position of a button
         */
        ValueAnimator buttonAnimatorY = ValueAnimator.ofFloat(pentagonVertices[position].y,
                startPositionY);
        buttonAnimatorY.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                button.setY((float) animation.getAnimatedValue());
                button.requestLayout();
            }
        });
        buttonAnimatorY.setDuration(300);

        /**
         * This will decrease the size of button
         */
        ValueAnimator buttonSizeAnimator = ValueAnimator.ofInt(170, 6);
        buttonSizeAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                button.getLayoutParams().width = (int) animation.getAnimatedValue();
                button.getLayoutParams().height = (int) animation.getAnimatedValue();
                button.requestLayout();
            }
        });
        buttonSizeAnimator.setDuration(300);

        /**
         * Add both x and y position update animation in
         *  animator set
         */
        buttonAnimator.play(buttonAnimatorX).with(buttonAnimatorY).with(buttonSizeAnimator);
        buttonAnimator.setStartDelay(exitDelay[position]);
        buttonAnimator.start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        baiduMap.setMyLocationEnabled(false);
        mapView.onDestroy();
        mapView = null;
        this.self = null;
    }
}
